<template>
    <div class="g-dialog-container" v-loading="loading" element-loading-text="加载中"
         element-loading-spinner="el-icon-loading">
        <div class="g-dialog-content">
            <el-form size="mini" label-suffix="：" :model="ruleForm" status-icon :rules="rules" ref="ruleForm"
                     label-width="100px" class="demo-ruleForm">
                <div class="shade-text">
                    <el-form-item label="名称" prop="name">
                        <el-input show-word-limit maxlength="20" placeholder="请输入" size="mini" v-model="ruleForm.name"
                                  clearable></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="phone">
                        <el-input show-word-limit maxlength="11" placeholder="请输入" size="mini" v-model="ruleForm.phone"
                                  clearable></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input show-word-limit maxlength="20" placeholder="请输入" size="mini" v-model="ruleForm.email"
                                  clearable></el-input>
                    </el-form-item>
                    <el-form-item label="标签" prop="tagId">
                        <el-select v-model="ruleForm.tagId" placeholder="请选择" size="mini" clearable>
                            <el-option v-for="item in tagOptions" :label="item.name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="区域" prop="regionId">
                        <el-select v-model="ruleForm.regionId" placeholder="请选择" size="mini" clearable
                                   @change="onChangeRegion">
                            <el-option v-for="item in regionOptions" :label="item.name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门" prop="deptId">
                        <el-select v-model="ruleForm.deptId" placeholder="请选择" size="mini" clearable @change="onChangeDeptId">
                            <el-option v-for="item in deptOptions" :label="item.name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="岗位" prop="positionId">
                        <el-select v-model="ruleForm.positionId" placeholder="请选择" size="mini" clearable>
                            <el-option v-for="item in positionOptions" :label="item.name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                  <el-form-item label="启用状态" prop="enabled">
                    <el-switch
                        v-model="ruleForm.enabled"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                    </el-switch>

                  </el-form-item>
                    <el-form-item label="备注" prop="remark" style="width: 80%;margin-bottom: 0">
                        <el-input
                            type="textarea"
                            :autosize="{ minRows: 8, maxRows: 8 }"
                            :maxlength="255"
                            resize="none"
                            size="mini"
                            placeholder="请输入"
                            v-model="ruleForm.remark"
                            show-word-limit
                        ></el-input>
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <div class="g-dialog-footer">
            <el-button type="primary" size="mini" icon="el-icon-circle-check" @click="handleSave">保存</el-button>
            <el-button type="primary" size="mini" icon="el-icon-circle-close" @click="handleCancel">取消</el-button>
        </div>
    </div>
</template>
<script>
// api
import { addPersonnel, getPersonnel, updatePersonnel } from '@/api/personnel'
import { getCommonList } from '@/api/common'

export default {
    props: {
        //判断是否进行修改
        isUpdate: {
            type: Boolean,
            default: true
        },
        // 人员id
        currentId: {
            type: [String, Number],
            default: ''
        }
    },
    data() {
        return {
            loading: false,
            ruleForm: {
                id: null,
                enabled: true,
                name: '',
                tagId: '',
                tagName: '',
                regionId: '',
                deptId: '',
                positionId: '',
                phone: '',
                email: '',
                remark: '',
                type: 1
            },
            rules: {
                name: [{ required: true, trigger: 'blur', message: '姓名不能为空' }],
                regionId: [{ required: true, trigger: 'blur', message: '区域不能为空' }],
                deptId: [{ required: true, trigger: 'blur', message: '部门不能为空' }],
                phone: [{ required: false, trigger: 'blur',  validator: (rule, value, callback) => {
                    const reg = /^1[3456789]\d{9}$/
                    if (reg.test(value)) {
                      callback()
                    } else {
                      return callback(new Error('请输入正确的手机号'))
                    }
                  }
                }],
                email: [{ required: false, trigger: 'blur', validator: (rule, value, callback) => {
                    const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/
                    const email = reg.test(value)
                    if (!email) {
                      callback(new Error('邮箱格式如:admin@163.com'))
                    } else {
                      callback()
                    }
                  }
                }],
            },
            tagOptions: [],
            regionOptions: [],
            deptOptions: [],
            positionOptions: []
        }
    },
    async created() {
        this.loading = true
        await getCommonList('tag').then(res => {
            if (res.status !== 200) return this.$msgPrompt.error(res.msg)
            this.tagOptions = res.obj
        }).catch(() => {
        })
        await getCommonList('region').then(res => {
            if (res.status !== 200) return this.$msgPrompt.error(res.msg)
            this.regionOptions = res.obj
        }).catch(() => {
        })
        await getCommonList('position').then(res => {
            if (res.status !== 200) return this.$msgPrompt.error(res.msg)
            this.positionOptions = res.obj
        }).catch(() => {
        })
        // 编辑页
        if (!this.isUpdate) return this.loading = false
        await this.getData()
    },
    methods: {
        async getData() {
            this.loading = true
            await getPersonnel(this.currentId)
                .then(res => {
                    this.loading = false
                    if (res.status !== 200) return this.$msgPrompt.error(res.msg)
                    for (let key in this.ruleForm) {
                        this.ruleForm[key] = res.obj[key]
                    }
                    if (res.obj.tagId) {
                      this.tagOptions.push({
                        id: res.obj.tagId,
                        name: res.obj.tagName
                      })
                    }
                })
                .catch(() => {
                })
            await getCommonList('dept', this.ruleForm.regionId).then(res => {
                if (res.status !== 200) return this.$msgPrompt.error(res.msg)
                this.deptOptions = res.obj
            }).catch(() => {
            })

        },
        onChangeRegion(val) {
            this.ruleForm.deptId = ''
            this.deptOptions = []
            getCommonList('dept', val).then(res => {
                if (res.status !== 200) return this.$msgPrompt.error(res.msg)
                this.deptOptions = res.obj
            })
        },
        onChangeDeptId(val) {
            this.ruleForm.positionId = ''
            this.positionOptions = []
            getCommonList('position', val).then(res => {
                if (res.status !== 200) return this.$msgPrompt.error(res.msg)
                this.positionOptions = res.obj
            })
        },
        //保存
        handleSave() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                  if (this.tagOptions && this.tagOptions.filter(item => item.id === this.ruleForm.tagId).length) {
                    this.ruleForm.tagName =  this.tagOptions.filter(item => item.id === this.ruleForm.tagId)[0].name
                  }
                  this.isUpdate ? this.update() : this.add()
                } else {
                    return false
                }
            })
        },
        //添加
        add() {
          this.$startLoading()
            addPersonnel(this.ruleForm).then((res) => {
                this.$endLoading()
                if (res.status != 200) return this.$msgPrompt.error(res.msg)
                this.$msgPrompt.success()
                this.$emit('succeed')
            })
        },
        //修改
        update() {
          this.$startLoading()
          console.log(this.ruleForm);
          updatePersonnel(this.ruleForm).then((res) => {
                this.$endLoading()
                if (res.status != 200) return this.$msgPrompt.error(res.msg)
                this.$msgPrompt.success()
                this.$emit('succeed')
            })
        },
        //取消
        handleCancel() {
            this.$emit('close')
        }
    }
}
</script>
<style scoped lang="scss">
.g-dialog-container {
    position: relative;
    width: 100%;
    height: 100%;

    .shade-text {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }

    .el-checkbox-group {
        display: flex;
        flex-wrap: wrap;

        .el-checkbox {
            min-width: 100px;
        }
    }


    .el-input,
    .el-select {
        width: 230px;
    }

    .el-textarea {
        width: 562px;
    }

    ul {

        width: 562px;
        height: 190px;
        overflow: auto;

    }

    .menu-tree {
        display: inline-block;
        vertical-align: top;
        width: 270px;

        ::v-deep .el-tree {
            .el-tree-node {
                &:focus > .el-tree-node__content {
                    background-color: transparent;
                }
            }

            .el-tree-node__content {
                &:hover {
                    background-color: transparent;
                }
            }
        }
    }
}
</style>
